package reflectionV2.dynamic_proxy;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Proxy;

/**
 * dynamic proxy: 其要求目标对象一定要实现接口
 *
 * @author ChangLiang
 * @date 2020/3/18
 */
public class UserDaoProxyFactory {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 接收的目标对象
     */
    private Object target;

    public UserDaoProxyFactory(Object target) {
        this.target = target;
    }

    public Object getProxyInstance() {
        return Proxy.newProxyInstance(
                target.getClass().getClassLoader(),
                // 这里需要把接口IUserDao传入
                target.getClass().getInterfaces(),
                (proxy, method, args) -> {
                    Object result;
                    String name = method.getName();
                    if ("save".equals(name)) {
                        logger.info("begin transaction");
                        result = method.invoke(target, args);
                        logger.info("end transaction");
                    } else {
                        result = method.invoke(target, args);
                    }
                    return result;
                });
    }
}
